﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Giraffe.Core.Common.Messengers;

namespace Giraffe.Core.Model
{
    public class ConversationManager: IConversationManager
    {
        private readonly IUser _user;

        public ConversationManager(IUser user)
        {
            _user = user;
            UpdateMessnegersSubscription();
        }

        #region Implementation of IConversationManager

        public IConversation StartConversation(IContact contact)
        {
            IMessenger contactMessenger = null;
            foreach (IMessenger messenger in _user.Messengers)
            {
                //todo change logic, needs messenger conversation priority
                IMessengerContact mContact = contact.MessengerContacts.FirstOrDefault(mc => mc.Messenger == messenger.MessengerType);
                if (mContact != null && messenger.ContactList.Contains(mContact))
                {
                    contactMessenger = messenger;
                    break;
                }
            }

            if (contactMessenger != null)
            {
                return new Conversation(contactMessenger, contact);
            }

            throw new ApplicationException("Cannot create conversation. Contact is not assigned for some messenger");
        }

        public event Action<IConversation> NewConversationRecieved;

        #endregion

        protected void UpdateMessnegersSubscription()
        {
            foreach (IMessenger messenger in _user.Messengers)
            {
                messenger.NewConversationRecieved += OnNewConversationRecieved;
            }
        }

        private void OnNewConversationRecieved(IMessengerContact messengerContact)
        {
            foreach (IContact contact in _user.Contacts)
            {
                if (contact.MessengerContacts.Contains(messengerContact))
                {
                    if (NewConversationRecieved != null)
                    {
                        IConversation conversation = StartConversation(contact);
                        NewConversationRecieved(conversation);
                        return;
                    }
                }
            }
        }
    }
}
